﻿using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;

namespace GoFishWeb.Models
{
    public class GoFishPlayer
    {
        protected GoFishPlayer()
        {
            Hand = new List<Card>();
            // needed for entity framework.  Must be no parameters and can not be private
        }

        public GoFishPlayer(string name)
        {
            Hand = new List<Card>();
            Name = name;
        }

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        [Required]
        public string Name { get; set; }

        public virtual List<Card> Hand { get; set; }

        public virtual GoFishGame Game { get; set; }

        public int CardCount
        {
            get { return Hand.Count; }
        }


        /// <summary>
        ///     Adds cards to the player's hand
        /// </summary>
        /// <param name="cards"></param>
        public void AddCardToHand(Card cards)
        {
            Hand.Add(cards);
        }

        /// <summary>
        ///     Adds cards to the player's hand
        /// </summary>
        /// <param name="cards"></param>
        public void AddCardsToHand(IEnumerable<Card> cards)
        {
            Hand.AddRange(cards);
        }

        /// <summary>
        ///     Retrieves any cards of the provided rank from the players hand
        /// </summary>
        /// <param name="rank"></param>
        /// <returns></returns>
        public IEnumerable<Card> TakeCards(CardRank rank)
        {
            var takenCards = Hand.Where(c => c.Rank == rank).ToList();
            Hand = Hand.Except(takenCards).ToList();
            return takenCards;
        }

        /// <summary>
        ///     Checks the players hands for books (all 4 suits of a particular rank), removes those cards
        /// </summary>
        /// <returns>List of ranks for which the player has books</returns>
        public IEnumerable<CardRank> PullOutBooks()
        {
            var books = new List<CardRank>();
            for (var i = 1; i <= 13; i++)
            {
                var rank = (CardRank) i;
                var cardsOfRank = Hand.FindAll(c => c.Rank == rank);

                if (cardsOfRank.Count == 4)
                {
                    books.Add(rank);
                    Hand.RemoveAll(cardsOfRank.Contains);
                }
            }

            return books;
        }
    }
}